﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NCS.IConnect.ApplicationContexts;
using Microsoft.SharePoint;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using JM.JCY.Common;
using System.Data;
using JM.JCY.Common.Utilities;
using System.IO;
using System.Threading;
using System.Text;
using System.Globalization;

namespace JM.JCY.SharePointComponent.PhotoAlbum.ViewAlbum
{
    public partial class ViewAlbumUserControl : UserControl,ICallbackEventHandler
    {
        public string appType
        {
            set;
            get;
        }
        public int appId
        {
            set;
            get;
        }
        public int _staffId
        {
            set;
            get;
        }

        public int _albumId
        {
            get;
            set;
        }

        public PhotoAlbumDataSet _albumDs
        {
            get
            {
                if (ViewState["View_albumDs"] != null)
                {
                    return (PhotoAlbumDataSet)ViewState["View_albumDs"];
                }
                else
                {
                    return new PhotoAlbumDataSet();
                }
            }
            set { ViewState["View_albumDs"] = value; }
        }

        public string _SpFolderId
        {
            get
            {
                if (ViewState["View_SpFolderId"] != null)
                {
                    return (string)ViewState["View_SpFolderId"];
                }
                else
                {
                    return "";
                }
            }
            set { ViewState["View_SpFolderId"] = value; }
        }

        public string _ContextAcronym
        {
            set;
            get;
        }

        static int PAGESIZE = JCYConstant.Pagination.PageSize;
        private int currentPageIndex;
        public string lastIndex = "1";
        public string CreatedBy
        {
            set { Session["ocp_album_createdBy"] = value; }
            get
            {
                if (Session["ocp_album_createdBy"] == null)
                {
                    return string.Empty;
                }
                else
                {
                    return Session["ocp_album_createdBy"].ToString();
                }
            }
        }

        private void LoadApplicationSettings()
        {
            _staffId = 11;
            if (ApplicationContext.Current.GetKeyValue("userId") != null)
            {
                _staffId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("userId"));
            }

            if (ApplicationContext.Current.GetKeyValue("appType") != null)
            {
                appType = ApplicationContext.Current.GetKeyValue("appType").ToString();
            }

            switch (appType)
            {
                case JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName:
                    appId = 0;
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName:
                    appId = _staffId;
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName:
                    if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                    {
                        appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                    }
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName:
                    if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                    {
                        appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                    }
                    break;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                LoadApplicationSettings();
                this.HiddenStaffId.Value = _staffId.ToString();

                if (!Page.IsPostBack)
                {
                    if (Request.QueryString["AlbumId"] != null)
                    {
                        _albumId = Int32.Parse(Request.QueryString["AlbumId"].ToString());
                        this.lbViewSlideShow.PostBackUrl = "/_layouts/SharePointComponent/viewslideshow.aspx?AlbumId=" + _albumId;
                        this.HiddenAlbumId.Value = _albumId.ToString();

                        Session["AlbumContentDT"] = null;
                        string callbackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveCallback", "context", false);
                        string callbackScript = string.Format("function CallServer(arg,context){{ {0}  }}", callbackReference);
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);

                        using (PhotoAlbumProxy accessProxy = new PhotoAlbumProxy())
                        {
                            _albumDs = accessProxy.getAlbumDbyAlbumId(_albumId);
                            _SpFolderId = _albumDs.T_SharePointObject.Rows[0][_albumDs.T_SharePointObject.SPFolderIdColumn.ColumnName].ToString();
                            Session["AlbumContentDT"] = accessProxy.GetAlbumContents(_albumId);
                            if (_albumDs.T_Album[0].AppType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName))
                            {
                                HiddenFieldAppType.Value = "P";
                                HiddenFieldAppId.Value = "0";
                            }
                            else if (_albumDs.T_Album[0].AppType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName))
                            {
                                HiddenFieldAppType.Value = "PS";
                                HiddenFieldAppId.Value = _albumId.ToString();
                            }
                            else if (_albumDs.T_Album[0].AppType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName))
                            {
                                HiddenFieldAppType.Value = "C";
                                HiddenFieldAppId.Value = _albumDs.T_Album[0].AppId.ToString();
                            }
                            else
                            {
                                HiddenFieldAppType.Value = "W";
                                HiddenFieldAppId.Value = _albumDs.T_Album[0].AppId.ToString();
                            }
                            LoadAlbumContents(_albumId, 1);

                            int createdBy = _albumDs.T_Album[0].Creator;
                            CreatedBy = createdBy.ToString();
                            string albumContextType = string.Empty;
                            string currentUserName = string.Empty;
                            //type is public
                            if (appType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName) || appType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName))
                            {
                                //current web is in mysite.
                                if (_staffId.Equals(_albumDs.T_Album[0].Creator))
                                {
                                    HiddenFieldEableEdit.Value = "T";//true.
                                }
                                else
                                {
                                    HiddenFieldEableEdit.Value = "F";//False.
                                }
                            }
                            else if (appType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName))
                            {
                                //the album is in workgroup
                                PhotoAlbumSearchDataSet.T_UserDepartmentDataTable department = accessProxy.GetAllDepartmentUsersById(appId);

                                DataRow[] rows = department.Select(string.Format("UserId={0}", _staffId));

                                if (rows.Length > 0)
                                {
                                    HiddenFieldEableEdit.Value = "T";
                                }
                                else
                                {
                                    HiddenFieldEableEdit.Value = "F";
                                }

                            }
                            else if (appType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName))
                            {
                                //the album is in committe
                                PhotoAlbumSearchDataSet.T_UserCommitteeDataTable committee = accessProxy.GetAllCommitteeUsersById(appId);

                                DataRow[] rows = committee.Select(string.Format("UserId={0}", _staffId));

                                if (rows.Length > 0)
                                {
                                    HiddenFieldEableEdit.Value = "T";
                                }
                                else
                                {
                                    HiddenFieldEableEdit.Value = "F";
                                }
                            }
                        }
                    }
                }
                string removeablum = Request.Params.Get("__EVENTTARGET");
                if (removeablum != null && removeablum.IndexOf("removeAlbum") > -1)
                {
                    lbRemoveThisAlbum_Click(sender, e);
                }
            }
            catch (Exception ex)
            {
                bool isok = JCYUtility.ExceptionHandle("view album loading", ex);
                if (isok == false)
                {
                    throw ex;
                }
            }
        }

        private void LoadAlbumContents(int albumId, int pageIndex)
        {
            try
            {
                PhotoAlbumSearchDataSet.T_AlbumContentDataTable contentDT = new PhotoAlbumSearchDataSet.T_AlbumContentDataTable();
                if (ViewState["AlbumContentDT"] == null)
                {
                    using (PhotoAlbumProxy proxy = new PhotoAlbumProxy())
                    {
                        contentDT = proxy.GetAlbumContents(albumId);
                    }
                    ViewState["AlbumContentDT"] = contentDT;
                }
                else
                {
                    contentDT = (PhotoAlbumSearchDataSet.T_AlbumContentDataTable)ViewState["AlbumContentDT"];
                }
                // load owner info
                if (contentDT.Rows.Count > 0)
                {
                    this.HiddenLastUpdatedTime.Value = contentDT[0].AlbumUpdatedTime.ToString("yyyy-MM-dd HH:mm:ss");
                    this.HiddenObjectId.Value = contentDT[0].AlbumObjectId.ToString();
                    string weburl = string.Empty;
                    
                    string creator = contentDT[0].CREATED_BY;
                    creator = creator.Substring(0, creator.Length > 30 ? 30 : creator.Length);
                    this.lblCreater.Text = "相册创建人： <a href='/PersonalSite/PersonalPages/PublicUser.aspx?StaffId=" + CreatedBy + "'>" + creator + "</a>";
                    string albumName = contentDT[0].AlbumName;
                    albumName = albumName.Substring(0, albumName.Length > 30 ? 30 : albumName.Length);
                    this.lblAlbumName.Text = albumName;
                    // substring tool tip if need
                    this.lblAlbumName.ToolTip = contentDT[0].AlbumName;
                    this.lblAlbumDesc.Text = contentDT[0].AlbumDescription;
                }

                //Calculate total page count
                int pages = (contentDT.Rows.Count % PAGESIZE == 0) ? contentDT.Rows.Count / PAGESIZE : (contentDT.Rows.Count / PAGESIZE) + 1;
                lastIndex = pages.ToString();
                HiddenFieldPageNum.Value = pages.ToString();
                if (pageIndex > pages)
                    pageIndex = pages;
                else if (pageIndex < 1)
                    pageIndex = 1;
                int startId = (pageIndex - 1) * PAGESIZE;
                int endId = pageIndex * PAGESIZE-1;

                DatalistViewAlbum.DataSource = contentDT.Select(string.Format("id>={0} and id<={1}", startId, endId));
                DatalistViewAlbum.DataBind();
            }
            catch (Exception ex)
            {
                bool isok = JCYUtility.ExceptionHandle("LoadAlbumContents in view album", ex);
                if (isok == false)
                {
                    throw ex;
                }
            }

        }

        public string GetCallbackResult()
        {
            //Return the rebind datalist's content
            return RenderControl(DatalistViewAlbum);
        }

        //Realize ICallbackEventHandler member RaiseCallbackEvent
        public void RaiseCallbackEvent(string eventArgument)
        {
            //int albumId = Int32.Parse(Request.QueryString["AlbumId"].ToString());
            currentPageIndex = Convert.ToInt32(eventArgument);
            LoadAlbumContents(int.Parse(this.HiddenAlbumId.Value), currentPageIndex);
        }

        private string RenderControl(Control control)
        {
            StringWriter writer1 = new StringWriter(CultureInfo.InvariantCulture);
            HtmlTextWriter writer2 = new HtmlTextWriter(writer1);

            control.RenderControl(writer2);
            writer2.Flush();
            writer2.Close();

            return writer1.ToString();
        }

        protected void DatalistViewAlbum_OnItemDataBound(object sender, DataListItemEventArgs e)
        {
            PhotoAlbumSearchDataSet.T_AlbumContentRow row = (PhotoAlbumSearchDataSet.T_AlbumContentRow)e.Item.DataItem;
            int contentObjId = row.SharePointObjectId;
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Literal viewLink = (Literal)e.Item.FindControl("LiteralViewMedia");
                viewLink.Text = "<a href='ViewMedia.aspx?MediaId=" + row.AlbumContentId + "&AlbumId=" + int.Parse(this.HiddenAlbumId.Value) + "'> <img src='" + row.ThumbNailImgUrl + "' alt='" + row.Description + "' width='159px' height='126px'></a>";
                Label lblLike = (Label)e.Item.FindControl("lblLikeCount");
                LinkButton lkbtLike = (LinkButton)e.Item.FindControl("lkbLike");

                string objectType = string.Empty;
                int[] likeResult = GetLikes(contentObjId);
                lblLike.Text = likeResult[0].ToString();
                if (likeResult[1] == 0)
                {
                    lkbtLike.Text = "喜欢";
                }
                else
                {
                    lkbtLike.Text = "不喜欢";
                }

                lkbtLike.Attributes.Add("onclick", "clickLike('" + contentObjId + "','" + lkbtLike.ClientID + "','" + lblLike.ClientID + "');return false;");
            }
        }

        protected void lbRemoveThisAlbum_Click(object sender, EventArgs e)
        {
            try
            {
                string siteName = string.Empty;
                switch (SPContext.Current.Web.ServerRelativeUrl.ToLower())
                {
                    case "/":
                        siteName = string.Empty;
                        break;
                    case "/mysite":
                        siteName = JCYConstant.SiteUrlName.MySite;
                        break;
                    case "/mydept":
                        siteName = JCYConstant.SiteUrlName.MyDept;
                        break;
                    case "/mycommittee":
                        siteName = JCYConstant.SiteUrlName.MyCommittee;
                        break;
                }

                SPInputs deleteInput = new SPInputs();
                deleteInput.SiteName = siteName;
                deleteInput.SPFolderID = _SpFolderId;
                SPOutputs deleteOut = JCYSharePointHelper.RemoveAlbum(deleteInput);
                if (deleteOut.IsError == false)
                {
                    IList<int> reciptid = new List<int>();
                    int createdContextId = Convert.ToInt32(Request.QueryString["AlbumId"].ToString());
                    string contextTypeName = string.Empty;
                    foreach (PhotoAlbumDataSet.T_SharePointObjectRow objRow in _albumDs.T_SharePointObject.Rows)
                    {
                        objRow.IsDeleted = true;
                        objRow.LAST_UPDATED_BY = SPContext.Current.Web.CurrentUser.Name;
                        objRow.LAST_UPDATED_TIME = DateTime.Now;
                    }

                    foreach (PhotoAlbumDataSet.T_AlbumRow albumRow in _albumDs.T_Album.Rows)
                    {
                        albumRow.IsDeleted = true;
                        albumRow.LatestUpdateTime = DateTime.Now;
                        albumRow.LAST_UPDATED_TIME = DateTime.Now;
                        albumRow.LAST_UPDATED_BY = SPContext.Current.Web.CurrentUser.Name;
                    }

                    foreach (PhotoAlbumDataSet.T_AlbumContentRow contentRow in _albumDs.T_AlbumContent.Rows)
                    {
                        contentRow.IsDeleted = true;
                        contentRow.LAST_UPDATED_BY = SPContext.Current.Web.CurrentUser.Name;
                        contentRow.LAST_UPDATED_TIME = DateTime.Now;
                    }
                    using (PhotoAlbumProxy funProxy = new PhotoAlbumProxy())
                    {
                        funProxy.CreateAlbumwithUpload(_albumDs);
                    }
                }
                else
                {
                    Exception ex = new Exception(deleteOut.Message.Replace("\r\n", ""));
                    bool isok = JCYUtility.ExceptionHandle("delete album", ex);
                    if (isok == false)
                    {
                        throw ex;
                    }
                    return;
                }

                Response.Redirect("AlbumCategories.aspx");
            }
            catch (Exception ex)
            {
                bool isok =JCYUtility.ExceptionHandle("delete album", ex);
                if (isok == false)
                {
                    throw ex;
                }
            }
        }
        private int[] GetLikes(int spobjectid)
        {
            int[] result = new int[2];
            using (PhotoAlbumProxy nfProxy = new PhotoAlbumProxy())
            {
                PhotoAlbumSearchDataSet.T_SearchLikeDataTable like = nfProxy.GetObjectLikCount(spobjectid, "pic");
                if (like.Rows.Count > 0)
                {
                    result[0] = like.Rows.Count;
                    DataRow[] lkes = like.Select(string.Format("StaffId={0}", _staffId));
                    if (lkes.Length == 1)
                    {
                        result[1] = 1;//1:to show unlike.
                    }
                    else
                    {
                        result[1] = 0;//0:to show like.
                    }
                }
                else
                {
                    result[0] = 0;
                    result[1] = 0;//0:to show like.
                }
            }

            return result;
        }

       
    }
}
